/*
 *
 * System2 Simulation Framework
 * Copyright (C) 2011 - 2012 Jacob Dawid
 * jacob.dawid@googlemail.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "context.h"
#include <stdlib.h>
#include <sstream>
#include <iostream>

namespace System2 {
    Context::Context() {
        m_context = v8::Context::New();
    }

    Context::~Context() {
        m_context.Dispose();
    }

    QString Context::serialize() {
        // TODO: Implement properly.
        return "<Context></Context>";
    }

    bool Context::unserialize(const QString& data) {
        (void)data;
        return true;
    }

    QString Context::execute(const QString& script) {
        v8::Locker locker;
        (void)locker;
        v8::Context::Scope contextScope(m_context);
        (void)contextScope;

        v8::TryCatch trycatch;
        v8::Handle<v8::Script> v8script
                = v8::Script::Compile(v8::String::New(script.toStdString().c_str()));

        if(trycatch.HasCaught()) {
            v8::Handle<v8::Value> exception = trycatch.Exception();
            v8::String::AsciiValue exceptionString(exception);
            return QString("[%1]").arg(*exceptionString);
        }

        v8::Handle<v8::Value> result = v8script->Run();
        if(result.IsEmpty()) {
            v8::Handle<v8::Value> exception = trycatch.Exception();
            v8::String::AsciiValue exceptionString(exception);
            return QString("[%1]").arg(*exceptionString);
        }
        v8::String::AsciiValue ascii(result);
        return QString(*ascii);
    }
}
